package com.cloud.lan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.lan.api.dto.req.DelReq;
import com.cloud.lan.api.dto.req.LanGoodsReq;
import com.cloud.lan.dao.LanGoodsImgMapper;
import com.cloud.lan.dao.LanGoodsLocationsMapper;
import com.cloud.lan.dao.LanGoodsMapper;
import com.cloud.lan.dao.LanStoreMapper;
import com.cloud.lan.entity.base.BaseResponse;
import com.cloud.lan.entity.base.exceptions.BaseException;
import com.cloud.lan.entity.enums.LanError;
import com.cloud.lan.entity.model.dataobject.LanGoodsDO;
import com.cloud.lan.entity.model.dataobject.LanGoodsImgDO;
import com.cloud.lan.entity.model.dataobject.LanGoodsLocationsDO;
import com.cloud.lan.entity.model.dataobject.LanStoreDO;
import com.cloud.lan.entity.model.pojo.LanGoodsLocationsResp;
import com.cloud.lan.entity.utils.VocUtil;
import com.cloud.lan.service.ILanGoodsService;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

import static com.cloud.lan.entity.utils.ConstantInterface.Enum.ConstantNumber.ONE;
import static com.cloud.lan.entity.utils.ConstantInterface.Enum.ConstantNumber.TOW;
import static com.cloud.lan.entity.utils.ConstantInterface.Enum.ConstantNumber.ZERO;

/**
 * <p>
 * 商品信息表 服务实现类
 * </p>
 *
 * @author xyqierkang@163.com
 * @since 2022-05-01
 */
@Slf4j
@Service
public class LanGoodsServiceImpl extends ServiceImpl<LanGoodsMapper, LanGoodsDO> implements ILanGoodsService {

    @Resource
    LanGoodsMapper lanGoodsMapper;

    @Resource
    LanGoodsImgMapper lanGoodsImgMapper;

    @Resource
    LanGoodsLocationsMapper lanGoodsLocationsMapper;

    @Resource
    LanStoreMapper lanStoreMapper;

    @Override
    public BaseResponse manageList(LanGoodsReq req) {
        log.info("#查询 商品信息表 列表 {}", req);
        LambdaQueryWrapper<LanGoodsDO> qw = new LambdaQueryWrapper<>();
        qw.eq(LanGoodsDO::getIsDeleted, false).orderByDesc(LanGoodsDO::getCreateTime);
        Page<LanGoodsDO> page = new Page<>(req.getPageIndex(), req.getPageSize());
        IPage<LanGoodsDO> pageList = lanGoodsMapper.selectPage(page, qw);
        pageList.getRecords().forEach(g -> {
            List<LanGoodsImgDO> photos = lanGoodsImgMapper.selectList(new LambdaQueryWrapper<LanGoodsImgDO>()
                    .eq(LanGoodsImgDO::getIsDeleted, false).
                    eq(LanGoodsImgDO::getImgType, ONE.getKey()).
                    eq(LanGoodsImgDO::getGoodsId, g.getId()));
            List<LanGoodsImgDO> details = lanGoodsImgMapper.selectList(new LambdaQueryWrapper<LanGoodsImgDO>()
                    .eq(LanGoodsImgDO::getIsDeleted, false).
                    eq(LanGoodsImgDO::getImgType, TOW.getKey()).
                    eq(LanGoodsImgDO::getGoodsId, g.getId()));
            List<LanGoodsLocationsDO> locations = lanGoodsLocationsMapper.selectList(new LambdaQueryWrapper<LanGoodsLocationsDO>()
                    .eq(LanGoodsLocationsDO::getIsDeleted, false).
                    eq(LanGoodsLocationsDO::getGoodsId, g.getId()));
            g.setPhotos(photos.stream().map(LanGoodsImgDO::getImgPath).collect(Collectors.toList()));
            g.setDetails(details.stream().map(LanGoodsImgDO::getImgPath).collect(Collectors.toList()));

            List<LanGoodsLocationsResp> locationsListResp = new ArrayList<>();
            locations.forEach(lo -> {
                LanGoodsLocationsResp lanGoodsLocationsResp = new LanGoodsLocationsResp();
                lanGoodsLocationsResp.setLocationId(lo.getStoreId());
                lanGoodsLocationsResp.setLink(lo.getLocations());
                locationsListResp.add(lanGoodsLocationsResp);
            });
            g.setLocations(locationsListResp);
        });
        return BaseResponse.success(pageList);
    }

    @Override
    public BaseResponse add(LanGoodsReq req) {
        log.info("#新增 商品信息表 {}", req);
        VocUtil.checkNullAttribute(new String[]{req.getName(), req.getDescription()},
                new String[]{"name", "description"}, LanError.ILLEGAL_PARAMS.getCode());
        LanGoodsDO lanGoodsDO = new LanGoodsDO();
        BeanUtil.copyProperties(req, lanGoodsDO, "photos", "details");
        LambdaQueryWrapper<LanGoodsDO> luwQw = new LambdaQueryWrapper<>();
        luwQw.eq(LanGoodsDO::getName, lanGoodsDO.getName());
        luwQw.eq(LanGoodsDO::getIsDeleted, false);
        if (lanGoodsMapper.selectCount(luwQw) > ZERO.getKey()) {
            log.error("{}", LanError.LAN_050001.getMsg());
            throw new BaseException(LanError.LAN_050001);
        }
        if (req.getPhotos().isEmpty()) {
            log.error("{}", LanError.LAN_050002.getMsg());
            throw new BaseException(LanError.LAN_050002);
        }
        lanGoodsDO.setGoodsNo(RandomUtil.randomNumbers(4));
        lanGoodsMapper.insert(lanGoodsDO);
        // 新增商品图片
        req.getPhotos().forEach(p -> {
            LanGoodsImgDO lanGoodsImgDO = new LanGoodsImgDO();
            lanGoodsImgDO.setGoodsNo(lanGoodsDO.getGoodsNo());
            lanGoodsImgDO.setGoodsId(lanGoodsDO.getId());
            lanGoodsImgDO.setImgPath(p);
            lanGoodsImgDO.setImgType(ONE.getKey());
            lanGoodsImgMapper.insert(lanGoodsImgDO);
        });

        // 新增商品详情图片
        req.getDetails().forEach(d -> {
            LanGoodsImgDO lanGoodsImgDO = new LanGoodsImgDO();
            lanGoodsImgDO.setGoodsNo(lanGoodsDO.getGoodsNo());
            lanGoodsImgDO.setGoodsId(lanGoodsDO.getId());
            lanGoodsImgDO.setImgPath(d);
            lanGoodsImgDO.setImgType(TOW.getKey());
            lanGoodsImgMapper.insert(lanGoodsImgDO);
        });

        // 新增商品购买地址
        req.getLocations().forEach(l -> {
            LanStoreDO storeDO = lanStoreMapper.selectById(l.getLocationId());
            if (ObjectUtil.isEmpty(storeDO)) {
                log.error("{}", LanError.LAN_040002.getMsg());
                throw new BaseException(LanError.LAN_040002);
            }
            LanGoodsLocationsDO lanGoodsLocationsDO = new LanGoodsLocationsDO();
            lanGoodsLocationsDO.setGoodsId(lanGoodsDO.getId());
            lanGoodsLocationsDO.setStoreId(l.getLocationId());
            lanGoodsLocationsDO.setGoodsNo(lanGoodsDO.getGoodsNo());
            lanGoodsLocationsDO.setLocations(l.getLink());
            lanGoodsLocationsMapper.insert(lanGoodsLocationsDO);
        });
        return BaseResponse.success();
    }

    @Override
    public BaseResponse update(LanGoodsReq req) {
        log.info("#更新 商品信息表 {}", req);
        VocUtil.checkNullAttribute(new String[]{String.valueOf(req.getId())},
                new String[]{"id"}, LanError.ILLEGAL_PARAMS.getCode());
        LanGoodsDO lanGoodsDO = lanGoodsMapper.selectById(req.getId());
        BeanUtil.copyProperties(req, lanGoodsDO, "goodsNo", "photos", "details");
        lanGoodsDO.setUpdateTime(DateUtil.date());
        lanGoodsMapper.updateById(lanGoodsDO);
        if (ObjectUtil.isNotEmpty(req.getPhotos())) {
            lanGoodsImgMapper.update(new LanGoodsImgDO(), new LambdaUpdateWrapper<LanGoodsImgDO>()
                    .set(LanGoodsImgDO::getIsDeleted, ONE.getKey())
                    .eq(LanGoodsImgDO::getImgType, ONE.getKey())
                    .eq(LanGoodsImgDO::getGoodsId, lanGoodsDO.getId()));
            // 新增商品图片
            req.getPhotos().forEach(p -> {
                LanGoodsImgDO lanGoodsImgDO = new LanGoodsImgDO();
                lanGoodsImgDO.setGoodsNo(lanGoodsDO.getGoodsNo());
                lanGoodsImgDO.setGoodsId(lanGoodsDO.getId());
                lanGoodsImgDO.setImgPath(p);
                lanGoodsImgDO.setImgType(ONE.getKey());
                lanGoodsImgMapper.insert(lanGoodsImgDO);
            });
        }

        if (ObjectUtil.isNotEmpty(req.getDetails())) {
            lanGoodsImgMapper.update(new LanGoodsImgDO(), new LambdaUpdateWrapper<LanGoodsImgDO>()
                    .set(LanGoodsImgDO::getIsDeleted, ONE.getKey())
                    .eq(LanGoodsImgDO::getImgType, TOW.getKey())
                    .eq(LanGoodsImgDO::getGoodsId, lanGoodsDO.getId()));
            // 新增商品详情图片
            req.getDetails().forEach(d -> {
                LanGoodsImgDO lanGoodsImgDO = new LanGoodsImgDO();
                lanGoodsImgDO.setGoodsNo(lanGoodsDO.getGoodsNo());
                lanGoodsImgDO.setGoodsId(lanGoodsDO.getId());
                lanGoodsImgDO.setImgPath(d);
                lanGoodsImgDO.setImgType(TOW.getKey());
                lanGoodsImgMapper.insert(lanGoodsImgDO);
            });
        }

        if (ObjectUtil.isNotEmpty(req.getLocations())) {
            lanGoodsLocationsMapper.update(new LanGoodsLocationsDO(), new LambdaUpdateWrapper<LanGoodsLocationsDO>()
                    .set(LanGoodsLocationsDO::getIsDeleted, ONE.getKey())
                    .eq(LanGoodsLocationsDO::getGoodsId, lanGoodsDO.getId()));
            // 新增商品购买地址
            req.getLocations().forEach(l -> {
                LanStoreDO storeDO = lanStoreMapper.selectById(l.getLocationId());
                if (ObjectUtil.isEmpty(storeDO)) {
                    log.error("{}", LanError.LAN_040002.getMsg());
                    throw new BaseException(LanError.LAN_040002);
                }
                LanGoodsLocationsDO lanGoodsLocationsDO = new LanGoodsLocationsDO();
                lanGoodsLocationsDO.setGoodsId(lanGoodsDO.getId());
                lanGoodsLocationsDO.setStoreId(l.getLocationId());
                lanGoodsLocationsDO.setGoodsNo(lanGoodsDO.getGoodsNo());
                lanGoodsLocationsDO.setLocations(l.getLink());
                lanGoodsLocationsMapper.insert(lanGoodsLocationsDO);
            });
        }
        return BaseResponse.success();
    }

    @Override
    public BaseResponse delete(DelReq req) {
        log.info("#删除 商品信息表 {}", req);
        VocUtil.checkNullAttribute(new String[]{String.valueOf(req.getId())}, new String[]{"id"}, LanError.ILLEGAL_PARAMS.getCode());
        LambdaUpdateWrapper<LanGoodsDO> luw = new LambdaUpdateWrapper<>();
        luw.set(LanGoodsDO::getIsDeleted, ONE.getKey())
                .set(LanGoodsDO::getUpdateTime, DateUtil.date())
                .eq(LanGoodsDO::getId, req.getId());
        lanGoodsMapper.update(new LanGoodsDO(), luw);
        return BaseResponse.success();
    }
}
